package controllers

import (
	"app/operatorLogs"
	"app/utils"
	"github.com/fwhezfwhez/errorx"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"reflect"
	"regexp"
	"strings"
)

var routes = make(map[string]reflect.Type)

func init() {
	addRoute("Permission", &Permission{})
	addRoute("User", &User{})
	addRoute("Log", &Log{})
}

func addRoute(controller string, d IController) {
	refV := reflect.ValueOf(d)
	refT := reflect.Indirect(refV).Type()
	routes[controller] = refT
}

type IController interface {
}

type Dashboard struct {
}

// API正常返回

func (dashboard *Dashboard) Response(data interface{}) gin.H {
	return gin.H{"errCode": 0, "data": data}
}

// API警告返回

func (dashboard *Dashboard) WarnResponse(code int, msg string) gin.H {
	logrus.Warn("code: ", code, " msg: ", msg)
	return gin.H{"errCode": code, "msg": msg}
}

// API错误返回

func (dashboard *Dashboard) ErrResponse(code int, err errorx.Error) gin.H {
	logrus.Error("code: ", code, " err: ", err)
	return gin.H{"errCode": code, "msg": err.Error()}
}

func actionNameFilter(str string) string {
	re := regexp.MustCompile(`_[a-zA-Z]`)
	str = re.ReplaceAllStringFunc(str, func(s string) string {
		return strings.ToUpper(s[1:])
	})

	return str
}

func Run(c *gin.Context) gin.H {
	controllerName := utils.UcFirst(c.Param("controller"))
	actionName := actionNameFilter(utils.UcFirst(c.Param("action")))
	controllerT, ok := routes[controllerName]
	if !ok {
		return gin.H{"-100": "系统错误"}
	}

	//flag, msg := checkSession(c, controllerName, actionName)
	//if flag == false {
	//	return gin.H{"errCode": -1, "msg": msg}
	//}

	refV := reflect.New(controllerT)
	method := refV.MethodByName(actionName)
	if !method.IsValid() {
		return gin.H{"-101": "系统错误"}
	}

	param := []reflect.Value{reflect.ValueOf(c)}
	response := method.Call(param)
	operatorLogs.Collect(c, response[0].Interface().(gin.H))
	return response[0].Interface().(gin.H)
}

func checkSession(c *gin.Context, controllerName string, actionName string) (bool, string) {
	if controllerName == "User" && actionName == "Login" {
		//ip验证
		//if c.ClientIP() != "117.186.215.226" {
		//	return false, "ip非法！"
		//}

		return true, ""
	}

	sessionId := c.GetHeader("SESSION-ID")
	if sessionId == "" || utils.SessionMagage.CheckSession(sessionId) == "" {
		return false, "登录过期，请重新登录系统！"
	}

	return true, ""
}
